/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ex3ldap;

import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

/**
 *
 * @author Patrick Füssinger
 * bis 28.11.2011
 * ITB5_2
 * Exercise 3 - LDAP
 * 
 * Diese Klasse stellt eine Verbindung zum Ldap-Verzeichnis der FHV her
 * und liest die Daten eines Users aus. Z.B. pfu5259 - Achtung, Passwort fehlt!
 */
public class LdapFHV {

    private Hashtable table = new Hashtable();

    public void findByUsername(String username, String pwd) throws NamingException {


        table.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        table.put(Context.PROVIDER_URL, "ldaps://ldap.fhv.at:636/");
        table.put(Context.SECURITY_PRINCIPAL, "uid=" + username + ",ou=fhv,ou=People,dc=uclv,dc=net");
        table.put(Context.SECURITY_CREDENTIALS, pwd);

        InitialDirContext idc = new InitialDirContext(table);

        String base = "ou=fhv,ou=People,dc=uclv,dc=net";

        Attributes match = new BasicAttributes();
        match.put(new BasicAttribute("uid", username));

        NamingEnumeration<SearchResult> namingEnum = idc.search(base, match);

        while (namingEnum.hasMore()) {
            SearchResult curr = namingEnum.next();
            Attributes attrs = curr.getAttributes();
            NamingEnumeration<? extends Attribute> aEnm = attrs.getAll();
            while (aEnm.hasMore()) {
                Attribute temp = aEnm.next();
                System.out.println(temp);
            }
        }


    }

    /**
     * Main
     * @param args 
     */
    public static void main(String[] args) {
        try {
            LdapFHV LdapFHV = new LdapFHV();
            
            LdapFHV.findByUsername("pfu5259", "passwort");
        } catch (NamingException ex) {
            Logger.getLogger(LdapFHV.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
